export class ReconnectingWebSocket {
  private url: string;
  private socket: WebSocket | null = null;
  private reconnectInterval: number = 5000; // 5秒重连间隔
  private heartbeatInterval: number = 15000; // 15秒心跳间隔
  private heartbeatTimer: NodeJS.Timeout | null = null;
  private reconnectTimer: NodeJS.Timeout | null = null;
  private isClosedByUser: boolean = true;

  constructor(url: string) {
    this.url = url;
    this.connect();
  }

  private connect() {
    if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
      console.log('已有连接存在，关闭现有连接后重新连接...');
      this.closeSocket();
    }
    this.isClosedByUser = false;
    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log('WebSocket连接成功');
      // this.startHeartbeat();
    };

    this.socket.onmessage = (event) => {
      this.onMessage(event.data);
    };

    this.socket.onclose = () => {
      console.log('WebSocket连接关闭');
      this.stopHeartbeat();
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
      }
      if (!this.isClosedByUser) {
        console.log('尝试重连...');
        this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval);
      }
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket错误:', error);
      this.socket?.close();
    };
  }

  private startHeartbeat() {
    this.stopHeartbeat();
    this.heartbeatTimer = setInterval(() => {
      if (this.socket?.readyState === WebSocket.OPEN) {
        this.socket.send('heartbeat');
        console.log('发送心跳');
      }
    }, this.heartbeatInterval);
  }

  private stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  public onMessage(data: any) {
    console.log('收到消息:', data);
    // 可以在外部重写此方法
  }

  public send(data: string) {
    if (this.socket?.readyState === WebSocket.OPEN) {
      this.socket.send(data);
    } else {
      console.error('WebSocket未连接，无法发送消息');
    }
  }

  public close() {
    this.isClosedByUser = true;
    this.stopHeartbeat();
    this.socket?.close();
  }

  private closeSocket() {
    this.stopHeartbeat();
    if (this.socket) {
      this.socket.onclose = null; // 防止触发自动重连
      this.socket.close();
      this.socket = null;
    }
  }

  public reconnect() {
    if (this.isClosedByUser || (this.socket && this.socket.readyState === WebSocket.CLOSED)) {
      console.log('尝试重新连接...');
      this.connect();
    } else {
      console.log('连接已经打开或正在重连中');
    }
  }

  public getStatus() {
    if (this.socket) {
      switch (this.socket.readyState) {
        case WebSocket.CONNECTING:
          return '连接中';
        case WebSocket.OPEN:
          return '已连接';
        case WebSocket.CLOSING:
          return '关闭中';
        case WebSocket.CLOSED:
          return '已关闭';
        default:
          return '未知状态';
      }
    }
    return '未初始化';
  }
}

/*// 使用示例
const ws = new ReconnectingWebSocket('wss://example.com/socket');

ws.onMessage = (data) => {
  console.log('自定义消息处理:', data);
};

// 发送消息
ws.send('Hello, WebSocket!');*/

// 关闭连接
// ws.close();

// 重新连接
// ws.reconnect();
